//
//  SearchTableViewController.m
//  news
//
//  Created by lanou on 15/12/19.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "SearchTableViewController.h"
#import "SearchResult.h"
#import "SearchBaikeTableViewCell.h"
#import "SearchNewsTableViewCell.h"
#import "BaikeViewController.h"
#import "MoreimageDetailsViewController.h"
#import "NewsDetailsViewController.h"

@interface SearchTableViewController ()

@property (nonatomic, retain) NSDictionary *baikeDic;

@property (nonatomic, retain) NSMutableArray *searchResultArray;

@end

@implementation SearchTableViewController

- (void)josnSearchResult
{
    NSString *urlString = [self.searchBarText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [NSString stringWithFormat:@"%@%@%@", @"http://c.m.163.com/search/comp/MA%3D%3D/20/",urlString, @".html?deviceId=NjEzRDZDMEUtNDgzNy00QzI1LUFDMTUtRTVDMUE4QTkyMDY1&version=NS40LjQ%3D&channel=5aS05p2h"];
    [LORequestManger GET:url success:^(id response) {
        
        NSDictionary *dic = (NSDictionary *)response;
        
        self.baikeDic = dic[@"baike"];
        
        self.searchResultArray = [[NSMutableArray alloc] init];
        
        for (NSDictionary *result in dic[@"doc"][@"result"]) {
            SearchResult *searchResult = [[SearchResult alloc] init];
            
            [searchResult setValuesForKeysWithDictionary:result];
            
            [self.searchResultArray addObject:searchResult];
        }
        
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self josnSearchResult];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    
    self.navigationItem.leftBarButtonItem = left;
    
    [self.tableView registerClass:[SearchBaikeTableViewCell class] forCellReuseIdentifier:@"baike"];
    
    [self.tableView registerClass:[SearchNewsTableViewCell class] forCellReuseIdentifier:@"newsResult"];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    if (self.baikeDic[@"url"]) {
        return 2;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    if (section || !self.baikeDic[@"url"]) {
        return self.searchResultArray.count;
    } else {
        return 1;
    }
}


#pragma mark -
#pragma mark ---加载单元格---

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section || !self.baikeDic[@"url"]) {
        
        SearchNewsTableViewCell *searchNewsCell = [tableView dequeueReusableCellWithIdentifier:@"newsResult" forIndexPath:indexPath];
        
        SearchResult *searchResult = self.searchResultArray[indexPath.row];
        NSString *title = [searchResult.title stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
        title = [title stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:title];
        
        
        NSRange range = [title rangeOfString:self.searchBarText];
        
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        
        searchNewsCell.titleLabel.attributedText = str;
        
        searchNewsCell.ptimeLabel.text = searchResult.ptime;
        
        return searchNewsCell;;
    } else {
        SearchBaikeTableViewCell *baikeCell = [tableView dequeueReusableCellWithIdentifier:@"baike" forIndexPath:indexPath];
        
        baikeCell.titleLanel.text = self.searchBarText;
        baikeCell.digestLabel.text = self.baikeDic[@"digest"];
        return baikeCell;
    }
    
    // Configure the cell...
}


#pragma mark -
#pragma mark ---点击进入详情---

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section || !self.baikeDic[@"url"]) {
        
        SearchResult *searchResult = self.searchResultArray[indexPath.row];
        
        if ([searchResult.skipType isEqualToString:@"doc"]) {
            NewsDetailsViewController *newsDetailsC = [[NewsDetailsViewController alloc] init];
           
            newsDetailsC.docid = searchResult.docid;
            
            [self.navigationController pushViewController:newsDetailsC animated:YES];
        } else {
            
            MoreimageDetailsViewController *moreImageDetails = [[MoreimageDetailsViewController alloc] init];
            
            moreImageDetails.photosetID = searchResult.skipID;
            
            [self.navigationController pushViewController:moreImageDetails animated:YES];
        }
        
    } else {
        
        BaikeViewController *baikeVC = [[BaikeViewController alloc] init];
        baikeVC.url = self.baikeDic[@"url"];
        UINavigationController *baikeNavC = [[UINavigationController alloc] initWithRootViewController:baikeVC];
        
        [self presentViewController:baikeNavC animated:YES completion:nil];
        
    }
}


#pragma mark -
#pragma mark ---添加表头---

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 30)];
    headerview.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, kWidth, 20)];
    
    if (section || !self.baikeDic[@"url"]) {
        label.text = @"新闻";
    } else {
        label.text = @"百科";
    }
    
    [headerview addSubview:label];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(20, 29, kWidth - 40, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [headerview addSubview:lineView];
    
    return headerview;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section || !self.baikeDic[@"url"]) {
        return 70;
    } else {
    return 80;
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
